<template>
  <!-- 空海派预排柜管理 -->
  <el-tabs
    v-model="activeNames"
    v-loading="loading1"
    type="border-card"
    @tab-click="handleClick"
  >
    <el-tab-pane label="海派" name="海派">
      <customContainer ref="configRef" :config="config1" />
    </el-tab-pane>
    <el-tab-pane label="空派" name="空派">
      <customContainer
        ref="config2Ref"
        :config="config2" 
      />
    </el-tab-pane>
    <el-dialog
      v-model="open"
      :close-on-click-modal="false"
      width="700px"
      title="添加"
    >
      <el-form
        ref="queryForm"
        :inline="true"
        :model="queryParams"
        label-width="90px"
      >
        <el-form-item label="客户单号" prop="waybillNo">
          <el-input
            v-model="queryParams.waybillNo"
            size="small"
            type="textarea"
            :autosize="{ minRows: 2, maxRows: 4 }"
            style="width: 193px;"
            placeholder="请输入客户单号"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item label="主转单号" prop="mainTransferOrderNo">
          <el-input
            v-model="queryParams.mainTransferOrderNo"
            size="small"
            type="textarea"
            :autosize="{ minRows: 2, maxRows: 4 }"
            style="width: 193px;"
            placeholder="请输入主转单号"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item label="系统订单号" prop="orderNo">
          <el-input
            v-model="queryParams.orderNo"
            size="small"
            type="textarea"
            :autosize="{ minRows: 2, maxRows: 4 }"
            style="width: 193px;"
            placeholder="请输入系统订单号"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item label="销售产品" prop="marketProducts">
          <el-select
            v-model="queryParams.marketProducts"
            filterable
            style="width: 200px;"
            placeholder="请选择销售产品"
            clearable
          >
            <el-option
              v-for="dict in dicts[DictDirection.产品]"
              :key="dict.salesProductCode"
              :label="dict.salesProductName"
              :value="dict.salesProductCode"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="国家" prop="consigneeCountry">
          <el-select
            v-model="queryParams.consigneeCountry"
            style="width: 193px;"
            placeholder="请选择国家"
          >
            <el-option
              v-for="dict in dicts[DictDirection.国家]"
              :key="dict.countryCode"
              :label="dict.countryChName"
              :value="dict.countryCode"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="选择日期">
          <el-date-picker
            v-model="dateRange"
            clearable
            type="daterange"
            style="width: 193px;"
            range-separator="-"
            size="small"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="yyyy-MM-dd HH:mm:ss"
          ></el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">
            搜索
          </el-button>
          <el-button type="info" @click="handleResetQuery">重置</el-button>
        </el-form-item>
      </el-form>
      <h3>排柜</h3>
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            type="primary"
            :disabled="multiple2"
            @click="handleConsolidation"
          >
            排柜
          </el-button>
        </el-col>
        <div class="ypg_title" style="float: right;">
          <span>黄色: 报关件</span>
          <span v-html="'&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'"></span>
          <span>红色: 扣件</span>
        </div>
      </el-row>
      <el-table
        v-loading="loading"
        border
        :row-class-name="tableRowClassName"
        :row-style="isRed"
        height="400px"
        :data="tableList1"
        @selection-change="handleSelectionChange1"
      >
        <el-table-column
          type="selection"
          align="center"
          width="45"
          fixef="left"
        ></el-table-column>
        <el-table-column
          label="客户单号"
          align="center"
          prop="waybillNo"
          min-width="150"
          show-overflow-tooltip
        ></el-table-column>
        <el-table-column
          label="客户名称"
          show-overflow-tooltip
          align="center"
          prop="customerCode"
          min-width="100"
        ></el-table-column>
        
        <el-table-column
          label="主转单号"
          min-width="250"
          show-overflow-tooltip
          align="center"
          prop="mainTransferOrderNo"
        >
          <template #default="{ row }">
            <copyText :text="row.mainTransferOrderNo" :link="false" />
          </template>
        </el-table-column>
        <el-table-column
          label="货物类型"
          align="center"
         
          prop="goodsType"
        ></el-table-column>
        <el-table-column
          label="实重"
          align="center"
          prop="receivingTotalWeight"
        ></el-table-column>
        <el-table-column
          label="材积重（方）"
          align="center"
          prop="receivingTotalWood"
          width="120"
        ></el-table-column>
        
        <el-table-column
          label="计费重"
          align="center"
          prop="receivingTotalCharging"
        ></el-table-column>
        <el-table-column
          label="销售产品"
          align="center"
          prop="marketProducts"
          min-width="90"
          show-overflow-tooltip
        ></el-table-column>
        <el-table-column
          label="总件数"
          align="center"
          prop="receivingTotal"
        ></el-table-column>
       
        <el-table-column
          label="收货日期"
          align="center"
          prop="orderTime"
          min-width="200"
        ></el-table-column>
        <el-table-column
          label="系统订单号"
          align="center"
          prop="orderNo"
          min-width="165"
          show-overflow-tooltip
        ></el-table-column>
      </el-table>
      <el-form inline>
        <el-row>
          <el-col :span="2">
            <el-form-item label="合计"></el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="实重:">
              {{ receivingTotalWeight }}
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="积重:">
              {{ receivingTotalWood }}
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="票数:">{{ colNum }}</el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="件数:">{{ receivingTotal }}</el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <pagination
        v-show="total1 > 0"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        :total="total1"
        @pagination="initList"
      />
    </el-dialog>
  </el-tabs>
  <el-dialog
    v-model="open2"
    width="1200px"
    title="排柜"
    :close-on-click-modal="false"
  >
    <el-form
      ref="forms"
      v-loading="loading"
      :model="form"
      :rules="rules"
      inline
      label-width="110px"
    >
      <el-form-item
        label="虚拟柜号"
        prop="cabinetNo"
      >
        <el-input v-model="form.cabinetNo" clearable></el-input>
      </el-form-item>
      <el-form-item label="运输类型：" prop="transportType" :rules="[{ required: true, message: '必填', trigger: ['blur', 'change'] }]">
        <el-select
          v-model="form.transportType"
          filterable
          clearable
          disabled
        >
          <el-option label="海派" value="1"></el-option>
          <el-option label="空派" value="2"></el-option>
        </el-select>
      </el-form-item>
    </el-form>
    <el-form>
      <el-row>
        <el-col :span="6">
          <el-form-item label="总实重：">
            {{ shipmentTotalWeight }}
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="总材积重：">
            {{ shipmentWoodCoefficient }}
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="票数：">{{ numberOfVotes }}</el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="件数：">{{ shipmentTotal }}</el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div class="footer">
      <el-button type="primary" @click="submit3">确认</el-button>
      <el-button @click="cacle3">取消</el-button>
    </div>
  </el-dialog>
  <edit
    ref="editRef"
    @refush="initData"
  ></edit>
</template>
<script lang="ts" setup>
import { ref, computed, getCurrentInstance, defineAsyncComponent } from 'vue'
import { ElButton, ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Download, Delete, Edit } from '@element-plus/icons-vue'
import { getlistTable, addCab, delCab, selectOrderPackage } from '@/api/expressManager/yuOrder'
import useDicts, { DictDirection } from '@/store/modules/dicts'
import userStore from '@/store/modules/user'

const copyText = defineAsyncComponent(() => import('@/components/copyText'))
const edit = defineAsyncComponent(() => import('./components/edit.vue'))
const user = userStore()
const activeNames = ref('海派')
const dicts = useDicts()
const dateRange = ref(null)
const configRef = ref(null)
const config2Ref = ref(null)
dicts.setDicts(DictDirection.产品)
dicts.setDicts(DictDirection.国家)
dicts.setDicts(DictDirection.运输类型)
const loading1 = ref(false)
const open = ref(false)
const open2 = ref(false)
// 切换tab栏
const handleClick = (row: { [key: string]: any }) => {
  loading1.value = true
  setTimeout(() => {
    loading1.value = false
  }, 500)
  activeNames.value = row.paneName
  if (activeNames.value == '海派') {
    queryParams.value.transportType = 1
    form.value.transportType = '1'
  } else {
    queryParams.value.transportType = 2
    form.value.transportType = '2'
  }
}
// 非多个禁用
const multiple = ref(true),
  multiple2 = ref(true),
  loading = ref(false),
  // 非单个禁用
  single = ref(true),
  single2 = ref(true),
  forms = ref(undefined),
  editRef = ref(undefined),
  // 查询
  {
    appContext: {
      config: {
        globalProperties: { $validateForm, $download },
      },
    },
  } = getCurrentInstance()
const deptIds = user.user.deptId
const queryParams = ref({
  pageNum: 1,
  pageSize: 10,
  waybillNo: undefined,
  transportType: 1,
  splittingStatus: 2,
  mainTransferOrderNo: undefined,
  orderNo: undefined,
  deptId: deptIds,
  marketProducts: undefined,
  consigneeCountry: undefined,
})
const total1 = ref(null)
const rules = {
  caseNo: [{ required: true, message: '必填项未输入', trigger: 'blur' }],
  cabinetNo: [{ required: true, message: '必填项未输入', trigger: 'blur' }],
  loadingLocation: [{ required: true, message: '必填项未输入', trigger: 'blur' }],
}
const tableRowClassName = (row) => {
  if (row.customsDeclaration === '报关件') {
    return 'textYellow'
  }
}
const isRed = (row) => {
  if (row.isFasteners == false) {
    return { color: 'red' }
  }
}
const form = ref({
  cabinetNo: undefined,
  transportType: '1',
})

const queryForm = ref(null)
const { proxy } = getCurrentInstance() as any
const tableList1 = ref()
// 删除
const handleDelete = () => {
  const id = JSON.parse(JSON.stringify(idss.value))

  ElMessageBox.confirm('此操作将删除该数据, 是否继续?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    delCab(id).then(res => {
      if (res.code == 200) {
        ElMessage.success('删除成功')
      }
    })
  })
}

const addHandle = () => {
  open.value = true
  initList()
}

// 修改
const editHand = () => {
  const status = JSON.parse(JSON.stringify(sts.value))
  if (status.value == '21') {
    console.log(status.value)
  } else {
    console.log(status.value, 111)
    editRef.value.open = true
    editRef.value.loading = true
    editRef.value.idss = JSON.parse(JSON.stringify(idss.value))
    editRef.value.transportTypes = JSON.parse(JSON.stringify(st.value))
    editRef.value.cab = JSON.parse(JSON.stringify(ca.value))
    editRef.value.initdata()
  }
}
// 导出
const exportYu = () => {
  const id = idss.value
  $download('order/cabinet/exportDetails', { ids: id }, `预排柜明细表格
  ${ new Date().getTime() }.xlsx`)
}
// 弹框搜索
const handleQuery = () => {
  initList()
}
const handleResetQuery = () => {
  proxy.$refs.queryForm.resetFields()
  initList()
}
// 排柜
const handleConsolidation = () => {
  open2.value = true
}
const submit3 = () => {
  const orderNoList1 = JSON.parse(JSON.stringify(orderNos.value))
 
  const data = {
    orderNoList: orderNoList1,
    cabinetNo: form.value.cabinetNo,
    transportType: form.value.transportType,
  }
  $validateForm(forms.value, () => {
    addCab(data).then(res => {
      if (res.code == 200) {
        open2.value = false
        proxy.$refs.forms.resetFields()
        initList()
        configRef.value.getList()
        config2Ref.value.getList()
        ElMessage.success('新增成功！')
      } else {
        ElMessage.error(res.msg)
      }
    })
  })
}
const cacle3 = () => {
  open2.value = false
  proxy.$refs.forms.resetFields()
}
const initList = () => {
  const query = queryParams.value
  loading.value = true
  selectOrderPackage(query).then(res => {
    if (res.code == 200) {
      proxy.tableList1 = res.data
      proxy.total1 = res.total
      loading.value = false
    }
  })
}
const initData = () => {
  configRef.value.getList()
  config2Ref.value.getList()
}
const receivingTotalWeight = ref(0)
const receivingTotalWood = ref(0)
const colNum = ref(0)
const receivingTotal = ref(0)
const shipmentTotalWeight = ref(0)
const shipmentWoodCoefficient = ref(0)
const numberOfVotes = ref(0)
const shipmentTotal = ref(0)
const st = ref([])
const ca = ref([])
const orderNoLists = ref([])
const orderNos = ref([])
const idss = ref([])
const sts = ref()
const handleTableSelect = (rows: { [key: string]: any }[]) => {
  orderNoLists.value = rows.map((item) => item.orderNo)
  idss.value = rows.map((item) => item.id)
  single.value = rows.length != 1
  multiple.value = !rows.length  
  st.value = rows.map((item) => item.transportType) 
  sts.value = rows.map((item) => item.status) 
  ca.value = rows.map((item) => item.cabinetNo)
}
const handleSelectionChange1 = (row: { [key: string]: any }[]) => {
  orderNos.value = row.map((item) => item.orderNo)
  
  const resl = row.some(el => el.isFasteners === false)
  if (resl) {
    ElMessage.error('红色标记的为扣件单，选择后不可操作')
  }
  const weight = row.reduce((total, el) => total + el.receivingTotalWeight, 0)
  const wood = row.reduce((total, el) => total + el.receivingTotalWood, 0)
  proxy.receivingTotalWeight = weight.toFixed(2)
  proxy.receivingTotalWood = wood.toFixed(2)
  proxy.receivingTotal = row.reduce((total, el) => total + el.receivingTotal, 0)
  proxy.shipmentTotalWeight = row.reduce((total, el) => total + el.receivingTotalWeight, 0)
  proxy.shipmentWoodCoefficient = row.reduce((total, el) => total + el.receivingTotalWood, 0)
  proxy.shipmentTotal = row.reduce((total, el) => total + el.receivingTotal, 0)
  proxy.numberOfVotes = row.length
  proxy.colNum = row.length
  single2.value = row.length != 1
  multiple2.value = !row.length
}
const config1 = computed({
  get() {
    return {
      query: {
        fields: [
          {
            label: '客户单号',
            prop: 'waybillNo',
          },
          {
            label: '虚拟柜号',
            prop: 'cabinetNo',
          },
          {
            label: '订单号',
            prop: 'orderNo',
          },
          {
            type: 'date-picker',
            label: '出货日期',
            prop: 'datetimePicker',
            option: {
              type: 'datetime',
            },
          },
        ],
        queryParams: {
          pageSize: 10,
          pageNum: 1,
          transportType: 1,
          waybillNo: undefined,
          cabinetNo: undefined,
          orderNo: undefined,
        },
        formOption: {},
      },
      btns: [
        {
          title: '删除',
          onClick: handleDelete,
          disabled: multiple.value,
          type: 'success',
          icon: Delete,
        },
        {
          title: '添加',
          icon: Plus,
          onClick: addHandle,
        },
        {
          title: '修改',
          onClick: editHand,
          type: 'success',
          icon: Edit,
          disabled: single.value,
        },
        {
          title: '导出',
          onClick: exportYu,
          type: 'warning',
          icon: Download,
          disabled: multiple.value,
        },
      ],
      table: {
        columns: [
          { type: 'selection', width: '55' },
          {
            label: '虚拟柜号', prop: 'cabinetNo', align: 'center',
          },
          { label: '总实重', prop: 'totalSolidWeight', align: 'center' },
          { label: '总材积重（方）', prop: 'totalVolumeWeight', align: 'center' },
          { label: '件数', prop: 'totalPiece', align: 'center' },
          { label: '票数', prop: 'votesNumber', align: 'center' },
          { label: '状态',
            prop: 'status',
            align: 'center', 
            autoFormatter: {
              dict: DictDirection.包裹状态,
              rowKey: 'status',
            } },
          { label: '运输类型',
            prop: 'transportType',
            align: 'center',
            autoFormatter: {
              dict: DictDirection.运输类型,
              rowKey: 'transportType',
            } },
          { label: '日期', prop: 'shipmentDate', align: 'center' },
          { label: '创建时间', prop: 'createDate', align: 'center' },
          { label: '创建人', prop: 'createUser', align: 'center' },
          { label: '备注', prop: 'remarks', align: 'center' },
        ],
        event: {
          onSelectionChange: (rows) => {
            handleTableSelect(rows)
          },
        },
      },
      api: getlistTable,
      customKey: 'express/mainBusiness/oceanShipping/arrayCabinetSupervise',
    }
  },
  set(v) {
    return v
  },
})
const config2 = computed({
  get() {
    return {
      query: {
        fields: [
          {
            label: '客户单号',
            prop: 'waybillNo',
          },
          {
            label: '虚拟柜号',
            prop: 'cabinetNo',
          },
          {
            label: '订单号',
            prop: 'orderNo',
          },
          {
            type: 'date-picker',
            label: '出货日期',
            prop: 'datetimePicker',
            option: {
              type: 'datetime',
            },
          },
        ],
        queryParams: {
          pageSize: 10,
          pageNum: 1,
          transportType: 2,
          waybillNo: undefined,
          cabinetNo: undefined,
          orderNo: undefined,
        },
        formOption: {},
      },
      btns: [
        {
          title: '删除',
          onClick: handleDelete,
          type: 'success',
          icon: Delete,
          disabled: multiple.value,
        },
        {
          title: '添加',
          icon: Plus,
          onClick: addHandle,
        },
        {
          title: '修改',
          onClick: editHand,
          icon: Edit,
          type: 'success',
          disabled: single.value,
        },
        {
          title: '导出',
          onClick: exportYu,
          type: 'warning',
          icon: Download,
          disabled: multiple.value,
        },
      ],
      table: {
        columns: [
          { type: 'selection', width: '55' },
          {
            label: '虚拟柜号', prop: 'cabinetNo', align: 'center',
          },
          { label: '总实重', prop: 'totalSolidWeight', align: 'center' },
          { label: '总材积重（方）', prop: 'totalVolumeWeight', align: 'center' },
          { label: '件数', prop: 'totalPiece', align: 'center' },
          { label: '票数', prop: 'votesNumber', align: 'center' },
          { label: '状态',
            prop: 'status',
            align: 'center',
            autoFormatter: {
              dict: DictDirection.包裹状态,
              rowKey: 'status',
            } },
          { label: '运输类型',
            prop: 'transportType',
            align: 'center',
            autoFormatter: {
              dict: DictDirection.运输类型,
              rowKey: 'transportType',
            } },
          { label: '日期', prop: 'shipmentDate', align: 'center' },
          { label: '创建时间', prop: 'createDate', align: 'center' },
          { label: '创建人', prop: 'createUser', align: 'center' },
          { label: '备注', prop: 'remarks', align: 'center' },
        ],
        event: {
          onSelectionChange: (rows) => {
            handleTableSelect(rows)
          },
        },
      },
      api: getlistTable,
      customKey: 'express/mainBusiness/oceanShipping/arrayCabinetSupervise',
    }
  },
  set(v) {
    return v
  },
})
</script>

<style lang="less" scoped>
.ypg_title {
  float: right;
  span:first-child {
    color: #fcaf17;
  }
  span:last-child {
    color: red;
  }
}
</style>
